package com.sxkf.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxkf.core.api.vo.R;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import com.sxkf.system.entity.SysDepart;
import com.sxkf.system.entity.SysUser;
import com.sxkf.system.model.DepartIdModel;
import com.sxkf.system.model.SysDepartTreeModel;
import com.sxkf.system.service.ISysDepartService;
import com.sxkf.system.service.ISysUserDepartService;
import com.sxkf.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 部门表 前端控制器
 * <p>
 * 
 * @Author: Steve @Since： 2019-01-22
 */
@RestController
@RequestMapping("/sys/sysDepart")
@Slf4j
public class SysDepartController {

	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	public StringRedisTemplate redisTemplate;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserDepartService sysUserDepartService;

	/**
	 * 查询数据 查出我的部门,并以树结构数据格式响应给前端
	 */
	@RequestMapping(value = "/queryMyDeptTreeList", method = RequestMethod.GET)
	public R<List<SysDepartTreeModel>> queryMyDeptTreeList() {
		R<List<SysDepartTreeModel>> r = new R<>();
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		try {
			if(oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals( CommonConstant.USER_IDENTITY_2 )){
				//update-begin--Author:liusq  Date:20210624  for:部门查询ids为空后的前端显示问题 issues/I3UD06
				String departIds = user.getDepartIds();
				List<SysDepartTreeModel> list = null;
				if(StringUtils.isNotBlank(departIds)){
					list = sysDepartService.queryMyDeptTreeList(departIds);
				}
				return R.success(CommonConstant.USER_IDENTITY_2.toString(),list);
			}else{
				return R.success(CommonConstant.USER_IDENTITY_1.toString(),null);
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return r;
	}

	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 */
	@RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
	public R<List<SysDepartTreeModel>> queryTreeList(@RequestParam(name = "ids", required = false) String ids) {
		List<SysDepartTreeModel> departList;
		if(oConvertUtils.isNotEmpty(ids)){
			departList = sysDepartService.queryTreeList(ids);
		}else{
			departList = sysDepartService.queryTreeList();
		}
		return R.success(departList);
	}

	/**
	 * 异步查询部门list
	 * @param parentId 父节点 异步加载时传递
	 * @param ids 前端回显是传递
	 * @param primaryKey 主键字段（id或者orgCode）
	 */
	@RequestMapping(value = "/queryDepartTreeSync", method = RequestMethod.GET)
	public R<List<SysDepartTreeModel>> queryDepartTreeSync(@RequestParam(name = "pid", required = false) String parentId, @RequestParam(name = "ids", required = false) String ids, @RequestParam(name = "primaryKey", required = false) String primaryKey) {
		List<SysDepartTreeModel> list = sysDepartService.queryTreeListByPid(parentId,ids, primaryKey);
		return R.success(list);
	}

	/**
	 * 获取某个部门的所有父级部门的ID
	 *
	 * @param departId 根据departId查
	 * @param orgCode  根据orgCode查，departId和orgCode必须有一个不为空
	 */
	@GetMapping("/queryAllParentId")
	public R queryParentIds(
			@RequestParam(name = "departId", required = false) String departId,
			@RequestParam(name = "orgCode", required = false) String orgCode
	) {
		try {
			JSONObject data;
			if (oConvertUtils.isNotEmpty(departId)) {
				data = sysDepartService.queryAllParentIdByDepartId(departId);
			} else if (oConvertUtils.isNotEmpty(orgCode)) {
				data = sysDepartService.queryAllParentIdByOrgCode(orgCode);
			} else {
				return R.error("departId 和 orgCode 不能都为空！");
			}
			return R.success(data);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.error(e.getMessage());
		}
	}

	/**
	 * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	public R<?> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
		String username = JwtUtil.getUserNameByToken(request);
		sysDepart.setCreateBy(username);
		sysDepartService.saveDepartData(sysDepart, username);
		return R.success();
	}

	/**
	 * 编辑数据 编辑部门的部分数据,并保存到数据库
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	public R<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
		String username = JwtUtil.getUserNameByToken(request);
		sysDepart.setUpdateBy(username);
		R<SysDepart> r = new R<>();
		SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
		sysDepartService.updateDepartDataById(sysDepart, username);
		//清除部门树内存
		//FindsDepartsChildrenUtil.clearSysDepartTreeList();
		//FindsDepartsChildrenUtil.clearDepartIdModel();
		return R.success();
	}
	
	 /**
     *   通过id删除
    * @param id
    * @return
    */
	//@RequiresRoles({"admin"})
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
   public R<SysDepart> delete(@RequestParam(name="id",required=true) String id) {
		sysDepartService.delete(id);
		//清除部门树内存
		//FindsDepartsChildrenUtil.clearSysDepartTreeList();
		// FindsDepartsChildrenUtil.clearDepartIdModel();
       return R.success();
   }


	/**
	 * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	public R<SysDepart> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		if (ids == null || ids.trim().isEmpty()) {
			return R.error("参数不识别！");
		}
		sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
		return R.success();
	}

	/**
	 * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
	 */
	@RequestMapping(value = "/queryIdTree", method = RequestMethod.GET)
	public R<List<DepartIdModel>> queryIdTree() {
		List<DepartIdModel> list = sysDepartService.queryDepartIdTreeList();
		return R.success(list);
	}
	 
	/**
	 * <p>
	 * 部门搜索功能方法,根据关键字模糊搜索相关部门
	 * </p>
	 */
	@RequestMapping(value = "/searchBy", method = RequestMethod.GET)
	public R<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord", required = true) String keyWord, @RequestParam(name = "myDeptSearch", required = false) String myDeptSearch) {
		//部门查询，myDeptSearch为1时为我的部门查询，登录用户为上级时查只查负责部门下数据
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departIds = null;
		if(oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals( CommonConstant.USER_IDENTITY_2 )){
			departIds = user.getDepartIds();
		}
		List<SysDepartTreeModel> treeList = this.sysDepartService.searchByKeyWord(keyWord,myDeptSearch,departIds);
		return R.success(treeList);
	}


	/**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysDepart sysDepart,HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysDepart> pageList = sysDepartService.list(queryWrapper);
        //按字典排序
        Collections.sort(pageList, new Comparator<SysDepart>() {
            @Override
			public int compare(SysDepart arg0, SysDepart arg1) {
            	return arg0.getOrgCode().compareTo(arg1.getOrgCode());
            }
        });
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
        mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:"+user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }



	/**
	 * 查询所有部门信息
	 */
	@GetMapping("listAll")
	public R<List<SysDepart>> listAll(@RequestParam(name = "id", required = false) String id) {
		R<List<SysDepart>> r = new R<>();
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
		query.orderByAsc(SysDepart::getOrgCode);
		if(oConvertUtils.isNotEmpty(id)){
			String[] arr = id.split(",");
			query.in(SysDepart::getId,arr);
		}
		List<SysDepart> ls = sysDepartService.list(query);
		return R.success(ls);
	}

	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 */
	@RequestMapping(value = "/queryTreeByKeyWord", method = RequestMethod.GET)
	public R<Map<String,Object>> queryTreeByKeyWord(@RequestParam(name = "keyWord", required = false) String keyWord) {
		Map<String,Object> map=new HashMap<>(5);
		try {

			List<SysDepartTreeModel> list = sysDepartService.queryTreeByKeyWord(keyWord);
			//根据keyWord获取用户信息
			LambdaQueryWrapper<SysUser> queryUser = new LambdaQueryWrapper<SysUser>();
			queryUser.eq(SysUser::getDelFlag,CommonConstant.DEL_FLAG_0);
			queryUser.and(i -> i.like(SysUser::getUsername, keyWord).or().like(SysUser::getRealname, keyWord));
			List<SysUser> sysUsers = sysUserService.list(queryUser);
			map.put("userList",sysUsers);
			map.put("departList",list);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return R.success(map);
	}

	/**
	 * 根据部门编码获取部门信息
	 *
	 * @param orgCode
	 * @return
	 */
	@GetMapping("/getDepartName")
	public R<SysDepart> getDepartName(@RequestParam(name = "orgCode") String orgCode) {
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
		query.eq(SysDepart::getOrgCode, orgCode);
		SysDepart sysDepart = sysDepartService.getOne(query);
		return R.success(sysDepart);
	}

	/**
	 * 根据部门id获取用户信息
	 *
	 * @param id
	 * @return
	 */
	@GetMapping("/getUsersByDepartId")
	public R<List<SysUser>> getUsersByDepartId(@RequestParam(name = "id") String id) {
		List<SysUser> sysUsers = sysUserDepartService.queryUserByDepId(id);
		return R.success(sysUsers);
	}
}
